package cn.wuxing.mediation.framework.config;

import cn.hutool.json.JSONObject;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

//@Component
public class DingTalkAuthenticationProviderdb implements AuthenticationProvider {

    private static final String APP_KEY = "wxznmtyydy_dingoa-MQn8oNR7juQj";
    private static final String APP_SECRET = "4OIwZh04Kt92c1054sI5Eh20Y8Ye4gn6a1AGfBU0";
    private static final String DINGTALK_API_DOMAIN = "https://oapi.dingtalk.com";

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String code = (String) authentication.getCredentials();

        UserInfo userInfo = getUserInfoFromDingTalk(code);

        if(userInfo== null){
            throw new AuthenticationException("CODE 不正确") {};
        }

        UserDetails userDetails = new CustomUserDetails(userInfo);
//        UserDetails userDetails = new Custom
        return new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return false;
    }

    @SneakyThrows
    public UserInfo getUserInfoFromDingTalk(String code) {
        String accessToken = getAccessToken(code);
        if (accessToken != null) {
            // 使用 access_token 和 code 调用获取用户信息的 API
            String userInfoApiUrl = DINGTALK_API_DOMAIN + "/rpc/oauth2/getuserinfo_bycode.json?access_token=" + accessToken + "&code=" + code;
            URL url = new URL(userInfoApiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 输出用户信息
            JSONObject jsonResponse = new JSONObject(response.toString());
            System.out.println("User Info: " + jsonResponse); // 格式化输出 JSON

        }
        // 替换YOUR_APP_KEY和YOUR_APP_SECRET
//        String url = "https://oapi.dingtalk.com/sns/getuserinfo?" +
//                "access_token=" + accessToken + "&code=" + code;
//        ResponseEntity<UserInfo> response = restTemplate.getForEntity(url, UserInfo.class);
        return null;
    }

    private static UserInfo getUserInfoByCode(String code) {
        try {
            // 获取 access_token
            String tokenApiUrl = DINGTALK_API_DOMAIN + "/gettoken?appkey=" + APP_KEY + "&appsecret=" + APP_SECRET;
            String accessToken = getAccessToken(tokenApiUrl);

            if (accessToken != null) {
                // 获取用户信息
                String userInfoApiUrl = DINGTALK_API_DOMAIN + "/rpc/oauth2/getuserinfo_bycode.json?access_token=" + accessToken + "&code=" + code;
                URL url = new URL(userInfoApiUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");

                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 解析 JSON 响应
                JSONObject jsonResponse = new JSONObject(response.toString());
                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(jsonResponse.getStr("userid"));
                userInfo.setUserName(jsonResponse.getStr("name"));

                return userInfo;
            }

        } catch (Exception e) {
            System.err.println("Error while getting user info: " + e.getMessage());
        }
        return null;
    }

    private static String getAccessToken(String tokenApiUrl) {
        try {
            URL url = new URL(tokenApiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            JSONObject jsonResponse = new JSONObject(response.toString());
            return jsonResponse.getStr("access_token");

        } catch (Exception e) {
            System.err.println("Error while getting access token: " + e.getMessage());
            return null;
        }
    }


    static class UserInfo {
        private String userId;
        private String userName;

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }
    }


//    private static String getAccessToken(String appKey, String appSecret) {
//        try {
//            String apiUrl = DINGTALK_API_DOMAIN + "/gettoken?appkey=" + appKey + "&appsecret=" + appSecret;
//            URL url = new URL(apiUrl);
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//            conn.setRequestMethod("GET");
//
//            // 读取响应
//            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//            String inputLine;
//            StringBuilder response = new StringBuilder();
//
//            while ((inputLine = in.readLine()) != null) {
//                response.append(inputLine);
//            }
//            in.close();
//
//            // 解析 JSON 响应
//            JSONObject jsonResponse = new JSONObject(response.toString());
//            return jsonResponse.getStr("access_token"); // 从响应中获取 access_token
//
//        } catch (Exception e) {
//            System.err.println("Error while getting access token: " + e.getMessage());
//            return null;
//        }
//    }




//    public String getAccessToken(String appId, String appSecret) throws ApiException {


//        ExecutableClient executableClient =ExecutableClient.getInstance();
//        executableClient.setAccessKey("appkey");
//        executableClient.setSecretKey("appsecrt");
//        executableClient.setDomainName("不同环境对应不同域名");
//        executableClient.setProtocal("https");
//        executableClient.init();
////executableClient要单例，并且使用前要初始化，只需要初始化一次
//
//        String api = "/gettoken.json";
//        GetClient getClient = executableClient.newGetClient(api);
////设置参数
//        getClient.addParameter("appkey", "37affba10137489c9cc8812b6b19590000003501");
//        getClient.addParameter("appsecret", "37affba10137489c9cc8812b6b19590000003501");
////调用API
//        String apiResult = getClient.get();
//
//        OapiSnsGettokenResponse response = null;
//
//        DingTalkClient client = new DefaultDingTalkClient(DINGDING_URL + "/sns/gettoken");
//        OapiSnsGettokenRequest request = new OapiSnsGettokenRequest();
//        request.setAppid(appId);
//        request.setAppsecret(appSecret);
//        request.setHttpMethod(METHOD_GET);
//        response = client.execute(request);
//        String body = response.getBody();
//        JSONObject jo = JSON.parseObject(body);
//        String errcode = jo.getString("errcode");
//        String access_token = null;
//        if ("0".equals(errcode)) {
//            access_token = (String) jo.get("access_token");
//        }
//        return access_token;
//    }
}
